/*
 * @lc app=leetcode.cn id=513 lang=typescript
 *
 * [513] 找树左下角的值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findBottomLeftValue(root: TreeNode | null): number {
  let maxDeepth = -1;
  let ans = 0;

  const dfs = (root: TreeNode | null, deepth: number): void => {
    if (root === null) return;
    // 第一次进入，记录val
    if (deepth > maxDeepth) {
      maxDeepth = deepth;
      ans = root.val;
    }
    dfs(root.left, deepth + 1);
    dfs(root.right, deepth + 1);
  };

  dfs(root, 0);
  return ans;
}
// @lc code=end
